import requests,csv,random,socket,datetime,json
import unittest
from setup_common import get_shared_ip,get_shared_headers,generate_url

class AsnTest(unittest.TestCase):
    test_results = []  # 用于收集测试结果

    def setUp(self):
        # 配置方法，定义了待测试的url，端口号和请求头
        # 获取主机名
        self.ip = get_shared_ip()
        # 配置url,即生成到货单号url和添加到货单的url
        self.asncodeurl = generate_url(self.ip, "asn/list")
        self.asnurl = generate_url(self.ip,  "asn/detail")
        # 获取共享的请求头
        self.headers = get_shared_headers()
        self.test_results = []  # 用于收集测试结果
        # 从 JSON 配置文件中读取配置信息
        with open("config.json", 'r') as config_file:
            self.config = json.load(config_file)
    def generator_asn_code(self):
        response = requests.post(url=self.asncodeurl, headers=self.headers, json={"creater": "cow11023"})
        if response.status_code == 200:
            data = response.json()
            asn_code = data["asn_code"]
            return asn_code
        else:
            return None

    def add_asn(self):
        responses = []  # 用于收集每次循环的 responses

        with open("supplier_20231008180456098.csv", 'r', newline='', encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile)
            header = next(csvreader)
            supplier_names = [supplier[0] for supplier in csvreader]

        with open("goods_list20231008180536513.csv", 'r', newline='', encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile)
            header = next(csvreader)
            goods_code_list = [code[0] for code in csvreader]

        for _ in range(self.config["asn_count"]["value"]):  ##定义了创建asn的数量
            try:
                asn_code = self.generator_asn_code()

                # 复制供应商列表和商品编码列表，确保每次循环都使用不同的随机选择
                current_supplier_names = supplier_names.copy()
                current_goods_code_list = goods_code_list.copy()

                supplier = random.choice(current_supplier_names)
                print(asn_code)
                print(supplier)
                if asn_code:
                    for _ in range(self.config["goods_per_asn"]["value"]):  # 每个asn里含有多少种商品
                        goods_code = random.choice(current_goods_code_list)
                        print(goods_code)
                        goods_qty = random.randint(1, 1000)  # 生成1到10000之间的goods_qty
                        print(goods_qty)
                        asn_data = {
                            "asn_code": asn_code,
                            "supplier": supplier,
                            "goods_code": [goods_code],
                            "goods_qty": [goods_qty],
                            "creater": "cow11023"
                        }
                        response = requests.request("POST", url=self.asnurl, json=asn_data, headers=self.headers).text
                        response_obj = json.loads(response)
                        responses.append(response_obj)
                        print(response)
                        response_obj["asn_code"] = asn_code
                        response_obj["goods_code"] = goods_code
                        response_obj["goods_qty"] = goods_qty
                else:
                    print("无法获取有效的 asn_code")
            except Exception as e:
                print(f"发生错误：{str(e)}")
        return responses

    def test_add_asn_01(self):
        # 执行测试用例
        responses = self.add_asn()

        for response in responses:
            result = response  # 解析每个 response 为 JSON 对象
            expected_response = {"detail": "success"}

            # 忽略 asn_code 和 goods_qty 的比较，只比较 detail 字段
            test = self.assertEqual(expected_response["detail"], result["detail"], "测试用例执行成功")

            # 将测试结果添加到 test_results 列表中
            self.test_results.append({
                "response": str(response),
                "asn_code": response.get("asn_code", ""),
                "goods_code": response.get("goods_code",""),
                "good_qty": response.get("goods_qty", ""),
                "测试结果": "通过" if test is None else "失败"
            })
        print("Test Results:", self.test_results)


    def tearDown(self):
        # 生成结果CSV文件
        # hasattr函数的作用是检测self 具有名为 'test_results' 的属性，即测试结果已经被收集，就会执行下面的代码块，生成测试结果的 CSV 文件
        if hasattr(self, 'test_results'):
            current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            csv_filename = f"添加到货通知书接口测试_result_{current_time}.csv"
            with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
                fieldnames = ["response", "asn_code", "goods_code","good_qty", "测试结果"]
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                writer.writeheader()
                writer.writerows(self.test_results)
                print(f"CSV 文件已生成：{csv_filename}")



if __name__ == '__main__':
    result = unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(AsnTest))
    if result.wasSuccessful():
        print("所有测试用例执行成功")
    else:
        print("存在测试用例执行失败")

    # 手动输出测试结果
    print("Test Results:", AsnTest.test_results)